package com.allen.admin.service.server.manager.impl;

import com.allen.admin.service.common.domain.AdminRole;
import com.xxx.dao.GenericDao;
import com.xxx.page.DataPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class AdminRoleManager {
	
	@Autowired
    private GenericDao dao;
	
	public AdminRole insert(AdminRole obj) {
		assert obj != null;
		
		obj.setCreatedTime(LocalDateTime.now());
		obj.setUpdatedTime(LocalDateTime.now());
		int affected = dao.insertAndReturnAffectedCount("AdminRoleMapper.insert", obj);
		if (affected > 0) {
			return obj;
		} else {
			return null;
		}
	}

	public AdminRole update(AdminRole obj) {
		assert obj != null;
		
		obj.setUpdatedTime(LocalDateTime.now());
		int affected = dao.updateByObj("AdminRoleMapper.update", obj);
		
		if (affected > 0) {
			return this.select(obj.getId());
		} else {
			return null;
		}
	}
	
	public AdminRole select(Integer id) {
		AdminRole obj = dao.queryUnique("AdminRoleMapper.selectById", id);
		return obj;
	}
	
	public List<AdminRole> select(List<Integer> ids) {
		assert ids != null && ids.size() > 0;
		Map<String, Object> map = new HashMap<String, Object>();
		
		if (ids.size() == 1) {
			map.put("id", ids.get(0));
		} else {
			map.put("ids", ids);
		}
		
		List<AdminRole> list = dao.queryList("AdminRoleMapper.selectByIds", map);
		return list;
	}
	
	public List<AdminRole> selectAllEnabled() {
		List<AdminRole> list = dao.queryList("AdminRoleMapper.selectAllEnabled");
		return list;
	}
	
	public AdminRole selectByName(String name) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", name);
		
		AdminRole obj = dao.queryUnique("AdminRoleMapper.select", map);
		return obj;
		
	}
	
	public AdminRole selectByCode(String code) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", code);
		
		AdminRole obj = dao.queryUnique("AdminRoleMapper.select", map);
		return obj;
	}

	public DataPage<AdminRole> queryPage(DataPage<AdminRole> dataPage, AdminRole qObj) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("order", dataPage.getOrder());
		map.put("orderBy", dataPage.getOrderBy());
		
		if (qObj.getDepartmentId() != null) {
			map.put("departmentId", qObj.getDepartmentId());
		}
		if (qObj.getStatus() != null) {
			map.put("status", qObj.getStatus());
		}
		
		dataPage = dao.queryPage(
				"AdminRoleMapper.countPage", 
				"AdminRoleMapper.queryPage", map, dataPage);
		
		return dataPage;
	}

}
